<template>
  <div v-loading="loading" class="app-container sales_forrecasts_edit">
    <div class="header_title_box">
      <h2>基本信息</h2>
    </div>
    <el-form :ref="formName" :model="formFieldsData" :rules="rules">
      <div class="select_form_box">
        <div class="filter-container">
          <el-form-item label="选择年份" prop="year" label-width="96px">
            <el-date-picker v-model="formFieldsData.year" type="year" value-format="yyyy" placeholder="-请选择-" class="input-with-select mr64" :disabled="!!id" />
          </el-form-item>
        </div>
      </div>
      <!-- 商品信息 -->
      <div class="header_title_box">
        <h2>商品明细信息</h2>
      </div>
      <div class="operation_button_box">
        <el-button size="middle" type="primary" icon="el-icon-circle-plus-outline" @click="showAddProductsDialog">添加商品</el-button>
        <el-button size="middle" type="primary" @click="delProducts">批量删除</el-button>
      </div>
      <div v-loading="loading">
        <el-table :data="formFieldsData.products" :row-class-name="tableRowClassName" border fit @selection-change="tableSelectHandler">
          <el-table-column type="selection" width="51" align="center" />
          <el-table-column label="缩略图" prop="goods_pic" align="center" width="120">
            <template slot-scope="scope">
              <thund :img="scope.row.goods_pic | shopThund" />
            </template>
          </el-table-column>
          <el-table-column label="系统sku" prop="goods_code" align="center" width="120" />
          <el-table-column label="中文名称" prop="goods_name" align="center" width="109" />
          <el-table-column label="英文名称" prop="goods_name_en" align="center" width="147" />
          <el-table-column label="商品分类" prop="category_text" align="center" width="96" />
          <el-table-column v-for="item in monthList" :key="item.id" :label="item.label" :prop="item.key" align="center" min-width="90">
            <template slot-scope="scope">
              <el-form-item :prop="`products[${scope.$index}][${item.key}]`" label-width="0px" :rules="numberRules" class="mt22">
                <el-input-number v-model="scope.row[item.key]" placeholder="手动输入" :precision="0" :min="1" :controls="false" :max="9999999999" class="sales_forrecasts_edit_number" />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <div class="dialog-footer-center">
      <span>
        <el-button type="primary" :loading="btnLoading" @click="handleSubmit">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </span>
    </div>
    <products-add-dialog ref="productsAdd" :url="productUrl" />
  </div>
</template>

<script>
import productAdd from '../../mixins/productAdd'
export default {
  name: 'SalesForecastsEdit',
  mixins: [productAdd],
  data() {
    return {
      id: '',
      info: {}, // 详情
      productUrl: '/product',
      formName: 'salesForecastsEdit',
      formFieldsData: {
        year: '',
        products: []
      },
      rules: {
        year: [{ required: true, message: '请选择年份', trigger: 'blur' }]
      },
      numberRules: [
        { required: true, message: '请输入销量', trigger: ['change', 'blur'] }
      ],
      loading: false,
      monthList: [
        {
          id: 11,
          label: '1月',
          key: 'jan'
        },
        {
          id: 12,
          label: '2月',
          key: 'feb'
        },
        {
          id: 13,
          label: '3月',
          key: 'mar'
        },
        {
          id: 14,
          label: '4月',
          key: 'apr'
        },
        {
          id: 15,
          label: '5月',
          key: 'may'
        },
        {
          id: 16,
          label: '6月',
          key: 'jun'
        },
        {
          id: 17,
          label: '7月',
          key: 'jul'
        },
        {
          id: 18,
          label: '8月',
          key: 'aug'
        },
        {
          id: 19,
          label: '9月',
          key: 'sep'
        },
        {
          id: 20,
          label: '10月',
          key: 'oct'
        },
        {
          id: 21,
          label: '11月',
          key: 'nov'
        },
        {
          id: 22,
          label: '12月',
          key: 'dec'
        }
      ],
      btnLoading: false
    }
  },
  watch: {
    $route(router) {
      this.checkRouterHasId(router)
    }
  },
  created() {
    const vm = this
    vm.checkRouterHasId(vm.$route)
  },
  methods: {
    // 给选中的列表加颜色
    tableRowClassName({ row, rowIndex }) {
      if (this.selectTableList.includes(row)) {
        return 'success-row'
      }
      return ''
    },
    // 检查路由是否有id
    checkRouterHasId(router) {
      const vm = this
      const id = router.params.id
      if (id) {
        vm.id = id
        vm.getInfo()
      }
    },
    // 详情
    getInfo() {
      const vm = this
      vm.loading = true
      vm.$http
        .get(`/sales-forecasts/${vm.id}`)
        .then((res) => {
          vm.info = res.data
          vm.formFieldsData.year = vm.info.year
          vm.formFieldsData.products = vm.info.products
          vm.loading = false
        })
        .catch(() => {
          vm.loading = false
        })
    },
    // 显示添加商品弹窗
    showAddProductsDialog() {
      const vm = this
      vm.$refs['productsAdd'].show({
        params: {
          status: 1,
          is_disable: 1
        },
        success({ data }) {
          vm.setProducts(data)
        }
      })
    },
    // 设置产品列表
    setProducts(data) {
      const vm = this
      data.forEach(e => {
        const index = vm.formFieldsData.products.findIndex(ele => ele.goods_id === e.id)
        if (index > -1) {
          vm.formFieldsData.products.splice(index, 1)
        }
        const item = {
          goods_id: e.id,
          goods_code: e.code,
          goods_name: e.name_ch,
          goods_name_en: e.name_en,
          category_name: e.category_name,
          category_text: e.category_text,
          goods_pic: e.image_url,
          packing_method: e.packing_method,
          number: '',
          type: 1
        }
        vm.monthList.forEach((e) => {
          item[e.key] = 1
        })
        vm.formFieldsData.products.push(item)
      })
    },
    // 取消
    handleCancel() {
      const vm = this
      vm.formFieldsData.year = ''
      vm.formFieldsData.products = []
      vm.$router.push({ path: '/storage/salesForecasts' })
    },
    // 确定
    handleSubmit() {
      const vm = this
      vm.$refs[vm.formName].validate((valid) => {
        if (valid) {
          const products = vm.formFieldsData.products.map((e) => {
            const obj = {
              goods_id: e.goods_id,
              category_name: e.category_name,
              goods_code: e.goods_code,
              goods_name: e.goods_name,
              goods_name_en: e.goods_name_en,
              goods_pic: e.goods_pic,
              packing_method: e.packing_method,
              jan: e.jan,
              feb: e.feb,
              mar: e.mar,
              apr: e.apr,
              may: e.may,
              jun: e.jun,
              jul: e.jul,
              aug: e.aug,
              sep: e.sep,
              oct: e.oct,
              nov: e.nov,
              dec: e.desc
            }
            return obj
          })
          const params = {
            year: vm.formFieldsData.year,
            products
          }
          vm.id ? vm.edit(params) : vm.add(params)
        }
      })
    },
    add(params) {
      const vm = this
      vm.btnLoading = true
      vm.$http
        .post('/sales-forecasts', params)
        .then((res) => {
          vm.$message.success('设置成功')
          vm.handleCancel()
          vm.btnLoading = false
        })
        .catch(() => {
          vm.btnLoading = false
        })
    },
    edit(params) {
      const vm = this
      vm.btnLoading = true
      vm.$http
        .put(`/sales-forecasts/${vm.id}`, params)
        .then((res) => {
          vm.$message.success('编辑成功')
          vm.handleCancel()
          vm.btnLoading = false
        })
        .catch(() => {
          vm.btnLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.sales_forrecasts_edit {
  .filter-container {
    padding-bottom: 0;
    border: none;
  }
}
.sales_forrecasts_edit .sales_forrecasts_edit_number {
  width: 70px;
}
.sales_forrecasts_edit .sales_forrecasts_edit_number ::v-deep .el-input__inner {
  padding: 0 5px;
}
</style>
